package cn.jeina.utils.validator;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;

import javax.validation.*;
import java.util.*;

/**
 * @author Summer
 * @Date: 2019-01-05 11:00
 * @Description: 接口效验
 * @versions:1.0
 */
public class ValidatorUtils {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * 返回list结构的检验结果数据
     * 必定返回list, 没有异常信息返回空list, 结果是字段名: 异常信息
     */
    public static List<String> getListValidResult(Object model, Class... validGroups) {
        Map<String, String> mapResult = getMapValidResult(model, validGroups);
        List<String> listResult = new ArrayList<>(mapResult.size());
        if (mapResult.isEmpty()) {
            return listResult;
        }
        for (Map.Entry<String, String> entry : mapResult.entrySet()) {
            listResult.add(entry.getKey() + ": " + entry.getValue());
        }
        return listResult;
    }

    /**
     * 返回map结构的检验结果数据
     * 必定返回map, 没有异常信息返回空map, 有的话key是字段名, v是异常信息
     */
    public static Map<String, String> getMapValidResult(Object model, Class... validGroups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<Object>> msgs = null;
        if (null == validGroups || validGroups.length == 0) {
            msgs = validator.validate(model);
        } else {
            msgs = validator.validate(model, validGroups);
        }
        Map<String, String> map = new HashMap<>(8);
        if (CollUtil.isNotEmpty(msgs)) {
            StringBuilder sb = new StringBuilder("参数校验异常: ");
            for (ConstraintViolation violation : msgs) {
                map.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return map;
    }

    /**
     * 校验, 如果错误会抛出异常 ValidationException
     *
     * @param model
     * @param validGroups
     */
    public static void valid(Object model, Class... validGroups) {
        Map<String, String> mapValidResult = getMapValidResult(model, validGroups);
        if (!mapValidResult.isEmpty()) {
            StringBuilder sb = new StringBuilder("参数校验异常: ");
            for (Map.Entry<String, String> entry : mapValidResult.entrySet()) {
                sb.append(entry.getKey()).append(" ");
                sb.append(entry.getValue()).append(" ");
            }
            sb.deleteCharAt(sb.length() - 1);
            throw new ValidationException(sb.toString());
        }
    }

    public static void validAllList(List<?> list, Class validGroup){
        Class[] validGroups = new Class[1];
        validGroups[0] = validGroup;
        validAllList(list, validGroups);
    }

    public static void validAllList(List<?> list, Class... validGroups) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < list.size(); ++i) {
            Object param = list.get(i);
            List<String> msgs = getListValidResult(param, validGroups);
            if (CollectionUtil.isNotEmpty(msgs)) {
                sb.append("索引为").append(i).append("的元素异常:\n");
                Iterator<String> it = msgs.iterator();

                while (it.hasNext()) {
                    String msg = it.next();
                    sb.append("\t").append(msg).append("\n");
                }
            }
        }

        if (sb.length() > 0) {
            throw new ValidationException("校验失败:\n" + sb);
        }
    }

}
